ListBoxes and ComboBoxes

Objectives


Discussion

Overview of ListBoxes and ComboBoxes

Add Items

Remove Items

Manipulating the Selected Item

Back to top


Demonstration

1. In this demo we will show how to add items to and remove items from a listbox.  We will do this in code.  It is very simple to add items to the Items property in the Properties Window.  You should add a few items just to make sure you understand.

2.  Add a new form to your unit 5 project.  Add three buttons (btnAdd, btnDeleteByItem, btnDeleteByIndex), a textbox (txtName) and a listbox (lstNames) so that your form looks like:

3.  Add the following code to the click event for the Add button:

lstNames.Items.Add(txtName.Text)

4.  Double-click the listbox.  In the Code window you should be in the SelectedIndexChanged event for the listbox.  This event fires when an item is selected.  The purpose of this code is just to show you what is happening and what the selecteditem and selectedindex properties do for you. Add the following code:

MessageBox.Show(lstNames.SelectedItem)
MessageBox.Show(lstNames.SelectedIndex)

5.  In the click event for the button Delete Selected Item by Name add the following code.  This code will remove the item that the user selected based on the item.  Study this code carefully.

lstNames.Items.Remove(lstNames.SelectedItem)

6.  In the click event for the button Delete Selected Item by Index add the following code.  This code will remove the item that the user selected based on the index.  Study this code carefully.

lstNames.Items.RemoveAt(lstNames.SelectedIndex)

7.  Run the program and add and delete items.  You need to select an item before you can select delete.

Back to top


Exercises

1. Modify the form that you created in the demo to prevent an error from occurring if the user does not select an item in the listbox before selecting the delete buttons.

2.  Create a form with two listboxes.  "Link" the listboxes so that if the user clicks on an item in one listbox, the item with the same index in the other listbox is also selected.

3.  Modify the demo program to include an array and a new button.  When the user clicks the button, the items in the listbox should be added to the array and displayed using the DisplayArray sub from the previous lesson.

4.  The CheckListBox control is similar to the ListBox and ComboBox controls.  Search for information about the CheckedListBox.  How is it different from the ListBox and ComboBox?

Back to top
Links & Help
Back to top